package cn.max.client;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.max.client.utils.EncodingUtil;
import cn.max.client.utils.FileCopyUtils;
import cn.max.client.utils.NamedValue;

/**
 *@author Val.(Valentine Vincent) E-mail:valer@126.com
 *@version 1.0
 *@date 2012-6-21
 *Instruction :
 **/
public class Client {

	public static final String METHOD_POST = "POST";
	public static final String METHOD_GET = "GET";

	private HttpURLConnection conn;

	public void setHeader(NamedValue pair) {
		conn.setRequestProperty(pair.getName(), pair.getValue());
	}

	public Client(String urlStr, NamedValue[] pairs, String method) {
		String paramStr = encodeParams(pairs);

		//build url
		String _URL = urlStr + "?" + paramStr;

		try {
			URL url = new URL(_URL);

			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod(method);
			conn.setConnectTimeout(300000);
			conn.setDoOutput(true);
			conn.setDoInput(true);

			//set the headers
			setHeader(new NamedValue("Content-type", "text/xml; charset=utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void setTimeout(int timeoutMs) {
		conn.setConnectTimeout(timeoutMs);
	}

	public Response execute(String message) {
		try {
			return execute(new ByteArrayInputStream(message.getBytes("UTF-8")));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public Response execute() {
		try {
			conn.connect();
			return new Response(conn.getInputStream(), conn);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}

	public Response execute(InputStream is) {
		try {
			conn.connect();
			OutputStream os = conn.getOutputStream();

			FileCopyUtils.copy(is, os);

			os.flush();

			return new Response(conn.getInputStream(), conn);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	protected static String encodeParams(NamedValue[] pairs) {
		if (pairs == null) {
			return "";
		}

		return EncodingUtil.formUrlEncode(pairs, "UTF-8");
	}

}
